package smartcarpool.smartspaceservice;

import java.util.Vector;

import android.app.IntentService;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import smartcarpool.logic.*;
import smartcarpool.ui.MainActivity;
import sofia_kp.KPICore;
import android.app.PendingIntent;

public class SmartSpaceService extends IntentService {


    public final static int INSERT_COMMAND = 1;
    public final static int QUERY_COMMAND = 2;
    public final static int UPDATE_COMMAND = 3;
    public final static int REMOVE_COMMAND = 4;
    public final static int SUBSCRIBE_COMMAND = 5;

    public final static int RESULT_FAILURE_JOIN = -1;
    public final static int RESULT_SUCCESS_INSERT = 100;
    public final static int RESULT_FAILURE_INSERT = 101;
    public final static int RESULT_SUCCESS_QUERY = 200;
    public final static int RESULT_FAILURE_QUERY = 201;
    public final static int RESULT_SUCCESS_REMOVE = 300;
    public final static int RESULT_FAILURE_REMOVE = 301;
    public final static int RESULT_SUCCESS_UPDATE = 400;
    public final static int RESULT_FAILURE_UPDATE = 401;
    public final static int RESULT_SUCCESS_SUBSCRIBE = 500;
    public final static int RESULT_FAILURE_SUBSCRIBE = 501;

    public final static String SMART_SPACE_PROFILE = "SS_Profile";
    public final static String SMART_SPACE_COMMAND = "SS_Command";
    public final static String SMART_SPACE_QUERY_ANSWER = "SS_AnswerQuery";
    public final static String SMART_SPACE_SUBSCRIBE_NEW_TRIPLES = "SS_SubscribeAnswer";
    public final static String SMART_SPACE_SUBSCRIBE_REMOVED_TRIPLES = "SS_SubscribeAnswer";
    public final static String TRIPLE_LIST = "TripleVector";
    public final static String TRIPLE_LIST_OLD = "TripleVectorOld";

	private KPICore kp;
	private String HOST;
	private int PORT;
	private String SPACE_NAME;
	private SmartSpaceProfile ssprofile;
    private FragmentManager fragmentManager;
    //private SmartSpaceUserProfile ssUserprofile;
    private TripleList inputTripleList;
    private TripleList inputTripleListOld;
    private PendingIntent pendingIntent;
    private SS_KP smartSpace;

    public SmartSpaceService() {
        super("SS_Service");
    }

    public SmartSpaceService(String name, SmartSpaceProfile ssprofile){ //, FragmentManager fragmentManager) {
        super(name);
        this.ssprofile = ssprofile;
        //this.fragmentManager = fragmentManager;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //ssprofile = intent.getExtras().getParcelable(SMART_SPACE_PROFILE);
        Log.d("SmartSpaceService", "Created");

    }

    @Override
    protected void onHandleIntent(Intent intent) {
        //String command = intent.getExtras().getString(SMART_SPACE_COMMAND);
        try {
            int command = intent.getExtras().getInt(SMART_SPACE_COMMAND);
            ssprofile = intent.getExtras().getParcelable(SMART_SPACE_PROFILE);
            pendingIntent = intent.getParcelableExtra(MainActivity.PARAM_PENDING);

            inputTripleList = intent.getExtras().getParcelable(TRIPLE_LIST);
            inputTripleListOld = intent.getExtras().getParcelable(TRIPLE_LIST_OLD);

//            Log.d("SmartSpaceService", ssprofile.getHost());

            smartSpace = SS_KP.getKP(ssprofile.getHost(), ssprofile.getPort(), ssprofile.getSpaceName());
            if (!smartSpace.isConnectionActive()){
                smartSpace.finalize();
                smartSpace.start();
                Log.d("SmartSpaceService", "pause main thread");
                smartSpace.join();
                Log.d("SmartSpaceService", "resume main thread");
            }
            if (!smartSpace.isConnectionActive()) {
                pendingIntent.send(SmartSpaceService.RESULT_FAILURE_JOIN);
            } else {
                switch (command){
                    case INSERT_COMMAND: {
                        SmartSpaceInsert ss_insert = new SmartSpaceInsert(smartSpace);
                        boolean result = ss_insert.insert(inputTripleList.toVector());
                        if (result){
                            //Log.d("SmartSpaceService", "Success insert");
                            pendingIntent.send(SmartSpaceService.RESULT_SUCCESS_INSERT);
                        } else {
                            //Log.d("SmartSpaceService", "Failed Insert");
                            pendingIntent.send(SmartSpaceService.RESULT_FAILURE_INSERT);
                        }
                        //insertTriplesToSmartSpace(inputTripleList.toVector());
                        break;
                    }
                    case QUERY_COMMAND: {
                        queryTriplesFromSmartSpace(inputTripleList.toVector());
                        break;
                    }
                    case UPDATE_COMMAND: {
                        updateTripleInSmartSpace(inputTripleList.toVector(),inputTripleListOld.toVector());
                        break;
                    }
                    case REMOVE_COMMAND: {
                        removeTriplesFromSmartSpace(inputTripleList.toVector());
                        break;
                    }
                    case SUBSCRIBE_COMMAND: {
                        subscribeToTripleFromSmartSpace(inputTripleList.toVector());
                        break;
                    }
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (PendingIntent.CanceledException e) {
            Log.e("SmartSpaceInsert. Pending Intent Error, Canceled", e.toString());
            e.printStackTrace();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }


	public void insertTriplesToSmartSpace(Vector<Vector<String>> tripleVectorToInsert){
		//System.out.println(ssprofile.toString());
		/*SmartSpaceInsert ssInsert = new SmartSpaceInsert(
                ssprofile.getHost(),
				ssprofile.getPort(),
				ssprofile.getSpaceName(),
				tripleVectorToInsert,
                pendIntent);
		Thread ssThread = new Thread(ssInsert);
		ssThread.start();*/

	}

    public void removeTriplesFromSmartSpace(Vector<Vector<String>> tripleVectorToInsert){
        //System.out.println(ssprofile.toString());
        SmartSpaceRemove ssRemove = new SmartSpaceRemove(
                ssprofile.getHost(),
                ssprofile.getPort(),
                ssprofile.getSpaceName(),
                tripleVectorToInsert,
                pendingIntent);
        Thread ssThread = new Thread(ssRemove);
        ssThread.start();
    }

    public void queryTriplesFromSmartSpace(Vector<Vector<String>> tripleVectorToQuery){
        //System.out.println(ssprofile.toString());
        SmartSpaceQuery ssQuery = new SmartSpaceQuery(
                ssprofile.getHost(),
                ssprofile.getPort(),
                ssprofile.getSpaceName(),
                tripleVectorToQuery,
                pendingIntent,
                SmartSpaceService.this);
        Thread ssThread = new Thread(ssQuery);
        ssThread.start();
    }

    public void subscribeToTripleFromSmartSpace(Vector<Vector<String>> tripleVectorToSubscribe){
        //System.out.println(ssprofile.toString());
        SmartSpaceSubscribe ssSubscribe = new SmartSpaceSubscribe(
                ssprofile.getHost(),
                ssprofile.getPort(),
                ssprofile.getSpaceName(),
                tripleVectorToSubscribe,
                pendingIntent,
                SmartSpaceService.this);
        Thread ssThread = new Thread(ssSubscribe);
        ssThread.start();
    }

    public void updateTripleInSmartSpace(Vector<Vector<String>> newTripleVector, Vector<Vector<String>> oldTripleVector){
        //System.out.println(ssprofile.toString());
        SmartSpaceUpdate ssSubscribe = new SmartSpaceUpdate(
                ssprofile.getHost(),
                ssprofile.getPort(),
                ssprofile.getSpaceName(),
                newTripleVector,
                oldTripleVector,
                pendingIntent);
        Thread ssThread = new Thread(ssSubscribe);
        ssThread.start();
    }


    public void onDestroy() {
        super.onDestroy();
        Log.d("SmartSpaceService", "Destroyed");
    }
}
